using UnityEngine;
using System.Collections;
using DanielSig.UnityExtensions;

public class Spawner : MonoBehaviour
{
	public GameObject SpawnPrefab;
	public int Interval;
	public int StartDelay;
	public float YPos;
	public int Max;
	public bool SpawnInBursts;
	public string Tag;
	
	private int _countDown;
	
	void Awake()
	{
		StartSpawning();
	}
	void StartSpawning()
	{
		_countDown = StartDelay;
		enabled = true;
	}
	void StopSpawning()
	{
		enabled = false;
	}
	void FixedUpdate()
	{
		for(int i = 0; i < GameCore.IterationsPerFrame; i++)
		{
			_countDown--;
			if(_countDown <= 0)
			{
				SpawnNow();
				_countDown = Interval;
			}
		}
	}
	
	[ContextMenu ("Spawn Now")]
	void SpawnNow()
	{
		if(SpawnInBursts)
		{
			int numToSpawn = Mathf.RoundToInt((Max - NumSpawned) * Random.value);
			for(int i = 0; i < numToSpawn; i++)
				SpawnOne();
		}
		else
		{
			SpawnOne();
		}
	}
	
	private void SpawnOne()
	{
		if(NumSpawned < Max)
		{
			Vector2 pos;
			do
			{
				pos = new Vector2(Mathf.FloorToInt(Random.value * 15.999999F), Mathf.FloorToInt(Random.value * 15.999999F));
			}
			while(SpawnPool.Pool.ContainsKey(pos));
			
			(Instantiate(SpawnPrefab, pos.Join(YPos).XZY(), Quaternion.identity) as GameObject).tag = Tag;
		}
	}
	private int NumSpawned
	{
		get{ return GameObject.FindGameObjectsWithTag(Tag).Length; }
	}
	void DestroyAllSpawns()
	{
		foreach(GameObject spawn in GameObject.FindGameObjectsWithTag(Tag))
		{
			Destroy(spawn);
		}
	}
}

